/*
 * Creator:     ML
 * CreatDate:   2019-09-12
 * descripts：  门诊医生医嘱录入 处方打印
*/
import React from 'react';
import { Row, Col, Divider, Button, Checkbox, message } from 'antd';
import { $http } from 'containers/config/https';
import store from '../../../store';
import { $loadTemplate } from '../../lodop/Common/Print.js';

class PrintingPrescription extends React.Component {
  constructor(porps) {
    super(porps);
    this.state = {
      baseInfo: {},//处方打印信息
      newData: [],
      ordPrescNo: "",
      checkFlag: false
    }
  }

  componentDidMount() {
    this.getPrescription()
    this.props.onRef(this)
  }

  getPrescription = () => {
    let data = {}
    let newDatas = []
    data = {
      params: [{
        admID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).admID : "",
        hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : {}
      }],
    }
    $http.post('urlS', this, {
      code: '03050087',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          res.result.prescInfo && res.result.prescInfo.map((item) => {
            item["checked"] = false
            if (item.printFlag != "Y") {
              item["checked"] = true
              newDatas.push(item.prescNo)
            }
          })
          this.setState({
            baseInfo: res.result,
            newData: newDatas,
          }, () => {
          })
        }
      },
    })
  }

  //选中打印
  handleCheck = (e, no, ordPrescNo) => {
    const { baseInfo, newData } = this.state
    let newDatas = this.state.newData
    let data = baseInfo
    data.prescInfo.map((item, i) => {
      if (item.No === no) {
        item.checked = e.target.checked
      }
    })
    this.setState({
      ordPrescNo: "",
      baseInfo: data
    })
    if (e.target.checked) {
      this.setState({
        ordPrescNo,
      })
      data.prescInfo.map((item, i) => {
        if (item.No === no) {
          newDatas.push(item.prescNo)
          this.setState({
            newData: newDatas
          })
        }
      })
    } else {
      this.setState({
        ordPrescNo: "",
      })
      newData && newData.map((item, i) => {
        if (item === ordPrescNo) {
          newDatas.splice(i, 1)
          this.setState({
            newData: newDatas
          })
        }
      })
    }
  }

  //点击打印
  handlePrit = () => {
    if (this.state.newData && this.state.newData.length == 0) {
      message.warning("请选择需要打印的处方单子")
      return
    }
    let data = {}
    data = {
      params: [{
        admID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).admID : "",
        userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
        hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
        groupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : "",
        ordPrescNo: this.state.newData || "",
      }],
    }
    $http.post('urlS', this, {
      code: '03050091',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          if (res.result && res.result.length > 0) {
            res.result.map((item, i) => {
              $loadTemplate(item.template, item.printStr);
            })
          }
          this.getPrescription()
        }
      },
    })
  }

  //国际化
  setMessage(name, message) {
    return this.props.localeProvider ? this.props.localeProvider[name][message] : ''
  }

  /**
  * @ByShizi: 上传或者撤销电子处方操作
  * Create 2022-09-06
  * */
  handleUploadAndCancel = async (rowData, status) => {
    try {
      let queryRes = await React.$asyncPost(this, '09030032', {
        params: [{
          prescNo: rowData?.prescNo || ''
        }]
      })
      if (queryRes.errorCode === '0') {
        let data = {
          params: [queryRes?.result?.inputParams],
          businessType: queryRes?.result?.businessType,
          funNO: queryRes?.result?.funNO,
          interfaceinfo: queryRes?.result?.interfaceinfo
        }
        let res = await React.$dllPost('PlatformDirectConnect', data, 'INSUNew/PTMedInsuInterface.dll', 'PTMedInsuInterface.InsuBusiness');
        if (res.errorCode === '0') {
          message.success(res.errorMessage || '成功');
          let INSUPrecNo = res.result && res.result.output && res.result.output.data && res.result.output.data.hi_rxno ? res.result.output.data.hi_rxno : ''; // 返回的医保处方号
          this.handlesaveUploadRecord(rowData?.prescNo, INSUPrecNo, status, data);
        } else {
          message.error(res.errorMessage || '失败');
        }
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 保存上传记录
  handlesaveUploadRecord = async (HISPrecNo, INSUPrecNo, status, parameterData) => {
    try {
      let res = await React.$asyncPost(this, '09030033', {
        params: [{
          HISPrecNo, // his处方号
          businessCode: 'prescUpload',
          INSUPrecNo, // 医保处方号，上传成功时，会返回
          status, // 上传B，撤销C
          parameterData, // 调dll入参
        }]
      });
      console.log(res)
    } catch (error) {
      console.log(error)
    }
  }

  render() {
    const { baseInfo } = this.state
    let tabsHeight = store.getState().tableHeight.y + 114 + 'px'
    return (
      <div className="userInfoDom">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <p style={{ margin: "0", }}>
            {baseInfo.head}
          </p>
          <Button style={{ display: (baseInfo.totalCount && baseInfo.totalCount ? "inline-block" : "none") }} type="primary" disabled={this.state.ordPrescNo && this.state.ordPrescNo.length == 0} onClick={this.handlePrit}>{this.props.localeProvider && this.props.localeProvider.PrintButtonPrint ? this.setMessage('PrintButtonPrint', 'descripts') : "打印"}</Button>
        </div>
        <Divider />
        <p style={{ margin: "0", display: (baseInfo.totalCount && baseInfo.totalCount ? "none" : "inline-block") }}>{this.props.localeProvider && this.props.localeProvider.PrintNoPrescription ? this.setMessage('PrintNoPrescription', 'descripts') : "暂无可打印处方"}</p>
        <div className="" style={{ display: "flex", width: "100%", flexWrap: "wrap", height: tabsHeight, overflow: "auto" }}>
          {
            baseInfo.prescInfo && baseInfo.prescInfo.map((item, i) => {
              return (
                <div style={{ width: "510px", height: "689px", overflow: "auto", margin: "0 20px 10px 0" }} >
                  <p style={{ color: "#1890ff", textAlign: "center", margin: "0", padding: "4px 0", fontWeight: "600" }}>{item.No ? item.No : "--"}/{baseInfo.totalCount}</p>
                  <div style={{ border: "1px solid #cfcfcf", padding: "8px", position: "relative" }}>
                    <span className="triangle-topleft"></span>
                    <div className="ribbon-green">
                      {item.printFlag != "Y" && this.props.localeProvider && this.props.localeProvider.PrintNotPrinted ? this.setMessage('PrintNotPrinted', 'descripts')
                        : (item.printFlag == "Y" && this.props.localeProvider && this.props.localeProvider.PrintPrinted ? this.setMessage('PrintPrinted', 'descripts') : "未打印")
                      }</div>
                    <Row className="title">
                      <div className="printingCheck">
                        <Checkbox style={{ color: "#0099FF" }} checked={item.checked} onChange={(e,) => this.handleCheck(e, item.No, item.prescNo)}>
                          {this.props.localeProvider && this.props.localeProvider.PrintButtonPrint ? this.setMessage('PrintButtonPrint', 'descripts') : "打印"}
                        </Checkbox>
                        <div style={{ marginTop: 6, textAlign: 'left' }}>
                          {item.uploadFlag === 'Y' ? <Button ghost size="small" type="primary" onClick={() => this.handleUploadAndCancel(item, 'B')}>上传</Button> : ''}
                          {item.cancelFlag === 'Y' ? <Button ghost size="small" type="danger" onClick={() => this.handleUploadAndCancel(item, 'C')}>撤销</Button> : ''}
                        </div>
                      </div>
                      <span style={{ fontSize: "24px", fontWeight: "600" }}>{item.admHospDesc && item.admHospDesc ? item.admHospDesc : "--"}</span>
                    </Row>
                    <Row className="title">
                      <span >{item.admHospENDesc && item.admHospENDesc ? item.admHospENDesc : "--"}</span>
                    </Row>
                    <Row className="title">
                      <span style={{ fontSize: "24px" }}>{item.prescName ? item.prescName : "--"}</span>
                      <span className="prescTypeSpan">{item.prescTypeDesc ? item.prescTypeDesc : "--"}</span>
                    </Row>
                    <Row className="title" style={{ marginBottom: "6px" }}>
                      <span >{item.prescENName ? item.prescENName : "--"}</span>
                    </Row>
                    <Row>
                      <Col span={8}>
                        <span>{this.props.localeProvider && this.props.localeProvider.PrintFabe ? this.setMessage('PrintFabe', 'descripts') : "费别："}{item.admReasonDesc && item.admReasonDesc ? item.admReasonDesc : "--"}</span>
                      </Col>
                      <Col span={14}>
                        <span>{this.props.localeProvider && this.props.localeProvider.PrintprescriptionNo ? this.setMessage('PrintprescriptionNo', 'descripts') : "处方号："}{item.prescNo && item.prescNo ? item.prescNo : "--"}</span>
                      </Col>
                    </Row>
                    <Row>
                      <Col span={8}>
                        <span >
                          {this.props.localeProvider && this.props.localeProvider.PrintName ? this.setMessage('PrintName', 'descripts') : "姓名："}
                          {item.patName && item.patName ? item.patName : "--"}
                        </span>
                      </Col>
                      <Col span={8}>
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintGender ? this.setMessage('PrintGender', 'descripts') : "性别："}
                          {item.patSexDesc && item.patSexDesc ? item.patSexDesc : "--"}
                        </span>
                      </Col>
                      <Col span={8}>
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintAge ? this.setMessage('PrintAge', 'descripts') : "年龄："}
                          {item.patAge && item.patAge ? item.patAge : "--"}
                        </span>
                      </Col>
                    </Row>
                    <Row>
                      <Col span={8}>
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintRegistrationNumber ? this.setMessage('PrintRegistrationNumber', 'descripts') : "登记号："}
                          {item.patNo && item.patNo ? item.patNo : "--"}
                        </span>
                      </Col>
                      <Col span={8}>
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintBillingDepartment ? this.setMessage('PrintBillingDepartment', 'descripts') : "开单科室："}
                          {item.loc && item.loc ? item.loc : "--"}
                        </span>
                      </Col>
                      <Col span={8}>
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintIssueDate ? this.setMessage('PrintIssueDate', 'descripts') : "开具日期："}
                          {item.prescDate && item.prescDate ? item.prescDate : "--"}
                        </span>
                      </Col>
                    </Row>
                    <Row>
                      <Col span={24}>
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintPhoneAddress ? this.setMessage('PrintPhoneAddress', 'descripts') : "电话/地址："}
                          {item.patMobile && item.patMobile ? item.patMobile : "--"}/{item && item.patAdress ? item.patAdress : "--"}
                        </span>
                      </Col>
                    </Row>
                    <Row>
                      <Col span={24} style={{ height: "21px", overflow: "auto" }}>
                        {this.props.localeProvider && this.props.localeProvider.PrintDiagnosis ? this.setMessage('PrintDiagnosis', 'descripts') : "诊断："}
                        {item.admDiag && item.admDiag ? item.admDiag : "--"}
                      </Col>
                    </Row>
                    <Divider />
                    <Divider />
                    <p style={{ display: (item.Detail && item.Detail.length != 0 ? "block" : "none"), margin: "0", position: "abssolute", left: "0", top: "0px", fontWeight: "600", fontSize: "16px" }}>Rp</p>
                    <div style={{ height: "176px", overflow: "hidden", overflowY: "auto" }}>
                      {item.Detail ? item.Detail.map((items, index) => {
                        return (
                          <div>
                            <Row className="marginTb" style={{ padding: (index == 0 ? "6px 26px 0" : "0 0 0 26px"), position: "relative" }}>
                              <Col className="smallTitle">
                                <span style={{ marginRight: "0", fontSize: "16px" }}>
                                  {index + 1}{"、"}
                                </span>
                                <span>
                                  {items.ordDesc}
                                </span>
                                <span>
                                  {items.spec}
                                </span>
                                <span>
                                  {items.qty}{items.qtyUomDesc}
                                </span>
                              </Col>
                              <Col style={{ margin: "0 0 0 26px" }}>
                                <span>
                                  {this.props.localeProvider && this.props.localeProvider.PrintUsage ? this.setMessage('PrintUsage', 'descripts') : "用法："}
                                  <span>{items.frequenceDesc}</span><span style={{ margin: "0 4px" }}>
                                    {this.props.localeProvider && this.props.localeProvider.PrintEach ? this.setMessage('PrintEach', 'descripts') : "每次"}
                                    {items.doseUnitStr}</span><span style={{ margin: "0 4px" }}> {items.usageDesc}</span>
                                  <span style={{ margin: "0 4px" }}> {items.ordPart}</span>
                                  <span style={{ margin: "0 4px" }}>{items.overdoseCauseStr}</span>
                                </span>
                              </Col>
                            </Row>
                            <Row>
                              {
                                items.childOrd && items.childOrd.map((subItem, subIndex) => {
                                  let a = subIndex + 1
                                  return (
                                    <Row className="marginTb" style={{ padding: "0 0 0 26px", position: "relative" }}>
                                      <Col className="smallTitle" style={{ marginLeft: "4px" }}>
                                        <span style={{ marginRight: "0" }}>
                                          {index + 1 + "." + a + "、"}
                                        </span>
                                        <span>
                                          {subItem.ordDesc}
                                        </span>
                                        <span>
                                          {subItem.spec}
                                        </span>
                                        <span>
                                          {subItem.qty}{subItem.qtyUomDesc}
                                        </span>
                                      </Col>
                                      <Col style={{ margin: "0 0 0 26px" }}>
                                        <span>
                                          {this.props.localeProvider && this.props.localeProvider.PrintUsage ? this.setMessage('PrintUsage', 'descripts') : "用法："}
                                          <span>{subItem.frequenceDesc}</span>
                                          <span style={{ margin: "0 4px" }}> {this.props.localeProvider && this.props.localeProvider.PrintEach ? this.setMessage('PrintEach', 'descripts') : "每次"}{subItem.doseUnitStr}</span>
                                          <span style={{ margin: "0 4px" }}> {subItem.usageDesc}</span>
                                          <span style={{ margin: "0 4px" }}> {subItem.ordPart}</span>
                                          <span style={{ margin: "0 4px" }}>{subItem.overdoseCauseStr}</span>
                                        </span>
                                      </Col>
                                    </Row>
                                  )
                                })
                              }
                            </Row>
                          </div>
                        )
                      }) :
                        <div className="line">
                        </div>
                      }
                      <Row style={{ display: (item.Detail && item.Detail.length > 5 ? "none" : "block"), marginTop: "4px" }}>
                        <Col style={{ textAlign: "center" }} span={24}> <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintTheBlank ? this.setMessage('PrintTheBlank', 'descripts') : "(以下空白)"}
                        </span></Col>
                      </Row>
                    </div>
                    <Row className="marginTb">
                      <Col span={15}>
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintServiceAmt ? this.setMessage('PrintServiceAmt', 'descripts') : "药事服务费："}
                          {item.serviceAmt && item.serviceAmt ? item.serviceAmt : "--"}
                        </span>
                      </Col>
                      <Col span={9}>
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintDoctor ? this.setMessage('PrintDoctor', 'descripts') : "医生："}
                          {item.doctorDesc && item.doctorDesc ? item.doctorDesc : "--"}
                        </span>
                      </Col>
                      <Divider />
                    </Row>
                    <Row>
                      <Col span={8} className="smallTitle">
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintReviewer ? this.setMessage('PrintReviewer', 'descripts') : "审核人："}
                          {item.auditUser && item.auditUser ? item.auditUser : "--"}</span>
                      </Col>
                      <Col span={8} className="smallTitle">
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintChecker ? this.setMessage('PrintChecker', 'descripts') : "核对人："}
                          {item.hdUser && item.hdUser ? item.hdUser : "--"}</span>
                      </Col>
                      <Col span={8} className="smallTitle">
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintDrugAmount ? this.setMessage('PrintDrugAmount', 'descripts') : "药品金额："}
                          {item.orderAmt && item.orderAmt ? item.orderAmt : "--"}</span>
                      </Col>
                    </Row>
                    <Row>
                      <Col span={8} className="smallTitle">
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintDeployer ? this.setMessage('PrintDeployer', 'descripts') : "调配人："}
                          {item.pyUser && item.pyUser ? item.pyUser : "--"}</span>
                      </Col>
                      <Col span={8} className="smallTitle">
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintDispenser ? this.setMessage('PrintDispenser', 'descripts') : "发药人："}
                          {item.dispUser && item.dispUser ? item.dispUser : "--"}</span>
                      </Col>
                      <Col span={8} className="smallTitle">
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintVisitDate ? this.setMessage('PrintVisitDate', 'descripts') : "就诊日期："}
                          {item.date && item.date ? item.date : "--"}</span>
                      </Col>
                    </Row>
                    <Divider />
                    <Divider />
                    <Row>
                      <Col>
                        {this.props.localeProvider && this.props.localeProvider.PrintTips ? this.setMessage('PrintTips', 'descripts') : "温馨提示："}
                        {this.props.localeProvider && this.props.localeProvider.PrintTipsPrescript ? this.setMessage('PrintTipsPrescript', 'descripts') : "1、本处方当日有效，过期作废;"}
                      </Col>
                      <Col style={{ marginLeft: "69px" }}>
                        {this.props.localeProvider && this.props.localeProvider.PrintTipsPrescriptB ? this.setMessage('PrintTipsPrescriptB', 'descripts') : "2、取药时请仔细核对药品;"}
                      </Col>
                      <Col style={{ marginLeft: "69px" }}>
                        {this.props.localeProvider && this.props.localeProvider.PrintTipsPrescriptC ? this.setMessage('PrintTipsPrescriptC', 'descripts') : " 3、依《中华人民共和国药品管理法》,药品一经发出,一律不得退换。"}

                      </Col>
                    </Row>
                  </div>
                </div>
              )
            })
          }
        </div>
      </div>
    )
  }
};

export default PrintingPrescription;